package com.sitanyun.merchant.guide.view.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.base.BaseActivity;
import com.sitanyun.merchant.guide.base.ToastUtil;
import com.sitanyun.merchant.guide.bean.MyUserInfoBean;
import com.sitanyun.merchant.guide.bean.PosterzxBean;
import com.sitanyun.merchant.guide.bean.UserVrBean;
import com.sitanyun.merchant.guide.callback.StringCallbacks;
import com.sitanyun.merchant.guide.frament.presenter.impl.MyFPresenterImpl;
import com.sitanyun.merchant.guide.frament.view.inter.IMyFView;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.weiht.DateUtils;
import com.sitanyun.merchant.guide.weiht.ImageLoadUtrils;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.sitanyun.merchant.guide.weiht.WxShareUtils;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMSendCallback;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import androidx.core.app.ActivityCompat;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 海报
 */
public class PosterActivity extends BaseActivity implements IMyFView {

    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.poster_wx)
    ImageView posterWx;
    @BindView(R.id.tv_save)
    TextView tvSave;
    @BindView(R.id.tv_wx)
    TextView tvWx;
    @BindView(R.id.tv_pyq)
    TextView tvPyq;
    @BindView(R.id.layout_poster)
    LinearLayout layout_poster;
    @BindView(R.id.poster_headImage)
    CircleImageView posterHeadImage;
    @BindView(R.id.store_img)
    ImageView storeImg;
    @BindView(R.id.tv_screenname)
    TextView tvScreenname;
    private MyFPresenterImpl mIMyFPresenter;

    private MyUserInfoBean myUserInfoBean;
    private Bitmap mBitmap;
    private static final int REQUEST_STATE_CODE = 1010;
    private int type;
    private int width = 120;
    private int height = 120;
    private Bitmap bitmap;
    private UserVrBean.CloudCustomDataBean cloudCustomDataBean = new UserVrBean.CloudCustomDataBean();

    @Override
    public int getLayoutId() {
        return R.layout.activity_poster;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        setFindViewById(true);
        setTitleStr("分享海报");
        initzx();
    }
    //二维码

    private void initzx() {
        String shar = getIntent().getStringExtra("shar");
        String staffid = SharedPreferenceUtil.getStringData("staffid");  //id
        String shops = getIntent().getStringExtra("shops"); //店铺名
        String names = getIntent().getStringExtra("scenname");  //人名
        String img = getIntent().getStringExtra("img");   //haibao
        Glide.with(PosterActivity.this).load(img).error(R.mipmap.poerbac).into(storeImg);
        tvScreenname.setText(names);
        String type = "";
        if (Urls.urls.contains("dev")) {
            type = "develop";
        //    Log.e("POST", "kaifa");
        } else if (Urls.urls.contains("test")) {
            type = "trial";
        //    Log.e("POST", "测试");
        } else if (Urls.urls.contains("sitanyun")) {
            type = "release";
        //    Log.e("POST", "正式");
        }

        String scenid = getIntent().getStringExtra("scenid");  //id
        // Urls.urls +"/vr?sceneId="
        String url = "sceneId=" + scenid + "&staffId=" + staffid + "&shareStaffId=" + staffid;
       // Log.e("POST", type);
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("page", "pages/vr/vr");
        hashMap.put("envVersion", type);
        hashMap.put("url", url);
        hashMap.put("usage", "VrShare");
        OkHttpUtils.postString()
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + SharedPreferenceUtil.getStringData("token"))
                .url(Urls.wxacode).content(new Gson().toJson(hashMap))
                .build().execute(new StringCallbacks() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                PosterzxBean posterzxBean = new Gson().fromJson(response, PosterzxBean.class);
                if (posterzxBean.getCode() == 0) {
                    //base64解码
                    bitmap = ImageLoadUtrils.stringToBitmap(posterzxBean.getData());
                    Glide.with(PosterActivity.this).load(bitmap).into(posterWx);
                } else {
                    ToastUtil.showToast(PosterActivity.this, posterzxBean.getMsg() + "");
                }
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        mIMyFPresenter = new MyFPresenterImpl(this);
        mIMyFPresenter.getuser();
    }

    @Override
    public void initView() {
//        String staffid = SharedPreferenceUtil.getStringData("staffid");  //id
//        String shops = getIntent().getStringExtra("shops"); //店铺名
//        String names = getIntent().getStringExtra("names");  //人名
//
//        String scenid = getIntent().getStringExtra("scenid");  //id
//        String img = getIntent().getStringExtra("img");   //haibao
//
//      Glide.with(PosterActivity.this).load(img).error(R.mipmap.poerbac).into(storeImg);
//        String url = Urls.urls +"/vr?sceneId=" + scenid + "&staffId=" + staffid + "&shareStaffId=" + staffid;
//        zxing(url);


    }

    //生成二维码
    private void zxing(String url) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //记得要自定义长宽
        BitMatrix encode = null;
        try {
            encode = qrCodeWriter.encode(url, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        int[] colors = new int[width * height];
        //利用for循环将要表示的信息写出来
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                if (encode.get(i, j)) {
                    colors[i * width + j] = Color.BLACK;
                } else {
                    colors[i * width + j] = Color.WHITE;
                }
            }
        }

        Bitmap bit = Bitmap.createBitmap(colors, width, height, Bitmap.Config.RGB_565);
        posterWx.setImageBitmap(bit);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation

        ButterKnife.bind(this);
    }

    @OnClick({R.id.tv_save, R.id.tv_wx, R.id.tv_pyq})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_save:
                if (DateUtils.isFastClick()) {
                    return;
                }
                // 保存海报图片
                type = 1;
                savePoster();
                break;
            case R.id.tv_wx:
                if (DateUtils.isFastClick()) {
                    return;
                }
                type = 2;
                if (mBitmap == null) {
                    savePoster();
                    WxShareUtils.shareImage(0, PosterActivity.this,
                            "wx7cb638590873ca35", mBitmap);
                } else {
                    WxShareUtils.shareImage(0, PosterActivity.this,
                            "wx7cb638590873ca35", mBitmap);
                }
        //分享
                initshare();
                break;
            case R.id.tv_pyq:
                if (DateUtils.isFastClick()) {
                    return;
                }
                type = 2;
                if (mBitmap == null) {
                    savePoster();
                    WxShareUtils.shareImage(1, PosterActivity.this,
                            "wx7cb638590873ca35", mBitmap);
                } else {
                    WxShareUtils.shareImage(1, PosterActivity.this,
                            "wx7cb638590873ca35", mBitmap);
                }
                //分享、
                initshare();


                break;
        }
    }
    // 分享统计IM数据
    private void initshare() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
        Date date = new Date(System.currentTimeMillis());
        cloudCustomDataBean = new UserVrBean.CloudCustomDataBean(
                "SHARE",
                SharedPreferenceUtil.getStringData("tonodeid")
                , getIntent().getStringExtra("scenid")
                , getIntent().getStringExtra("scenname")
                , getIntent().getStringExtra("storeid")
                , getIntent().getStringExtra("storename")
                , SharedPreferenceUtil.getStringData("staffid")
                , SharedPreferenceUtil.getStringData("staffname")
                , "1"
                , ""
                , ""
                , "0", simpleDateFormat.format(date));
        V2TIMMessage v2TIMMessage = V2TIMManager.getMessageManager().createCustomMessage("5".getBytes());
        // 发送消息
        String msgs = JSON.toJSONString(cloudCustomDataBean);
        v2TIMMessage.setCloudCustomData(msgs);
        V2TIMManager.getMessageManager().sendMessage(v2TIMMessage, "cid_1", null, V2TIMMessage.V2TIM_PRIORITY_DEFAULT, false, null, new V2TIMSendCallback<V2TIMMessage>() {
            @Override
            public void onError(int code, String desc) {
                Log.e("SHARE", code + "" + desc);
            }

            @Override
            public void onSuccess(V2TIMMessage v2TIMMessage) {
                Log.e("SHARES", "onSuccess");
            }

            @Override
            public void onProgress(int progress) {
                Log.e("SHARE", "progress");
            }
        });

    }


    private void savePoster() {
        // 1.View截图
        layout_poster.setDrawingCacheEnabled(true);
        // 重新测量View
        layout_poster.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        // 2.创建一个Bitmap
        mBitmap = layout_poster.getDrawingCache();
        // 3.保存到SD卡
        if (mBitmap != null) {
            //判断是否为Android 6.0 以上的系统版本，如果是，需要动态添加权限
            if (Build.VERSION.SDK_INT >= 23) {
                requestPermissionss();
            } else {
                saveToLocal(mBitmap);
            }
        }

    }

    //动态权限
    private void requestPermissionss() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, REQUEST_STATE_CODE);
        } else {
            saveToLocal(mBitmap);
        }
    }

    /**
     * 保存一张Bitmap图到本地
     */
    private void saveToLocal(Bitmap bitmap) {
        try {
            File appDir = new File(Environment.getExternalStorageDirectory(), "Poster");
            // 没有目录创建目录
            if (!appDir.exists()) {
                appDir.mkdir();
            }
            File file = new File(appDir, "view_" + System.currentTimeMillis() + ".jpg");
            FileOutputStream out;
            try {
                out = new FileOutputStream(file);
//                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                    out.flush();
                    out.close();
                    // 通知图库更新
                    Uri uri = Uri.fromFile(file);
                    Intent scannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
                    sendBroadcast(scannerIntent);
                    if (type == 1) {
                        Toast.makeText(this, "保存图片到相册成功", Toast.LENGTH_SHORT).show();
                    }

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public <T> T request(int requestFlag) {
        return null;
    }

    @Override
    public <T> void response(T response, int responseFlag) {
        if (responseFlag == IMyFView.RESPONSE_ONE) {
            myUserInfoBean = (MyUserInfoBean) response;
            if (myUserInfoBean.getCode() == 0) {
                Glide.with(PosterActivity.this).load(myUserInfoBean.getData()
                        .getHeadUrl()).apply(new RequestOptions().error(R.mipmap.cimg)).into(posterHeadImage);
                //     posterName.setText(myUserInfoBean.getData().getEnterprise() + "");
                tvName.setText(myUserInfoBean.getData().getName() + "");

            } else {
                ToastUtil.showToast(PosterActivity.this, myUserInfoBean.getMsg() + "");
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_STATE_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    saveToLocal(mBitmap);
                } else {
                    Toast.makeText(this, "没有开启存储权限，保存失败!", Toast.LENGTH_LONG).show();
                    return;
                }
                break;
            default:
                break;
        }
    }

    @OnClick(R.id.store_img)
    public void onViewClicked() {
    }
}
